package com.kehutong.work.order.manage.admin;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.util.Objects;
import com.kehutong.common.ExcelUtil;
import com.kehutong.common.util.Token;
import com.kehutong.work.order.manage.entity.WorkOrderManage;
import com.kehutong.work.order.manage.entity.WorkOrderManageSetting;
import com.kehutong.work.order.manage.service.WorkOrderManageService;
import com.kehutong.work.order.manage.service.WorkOrderSettingService;

/**
 * 管理后台-工单
 */
@MvcAction
@ReqMapping("/admin/work/order/manage")
public class WorkOrderController {

    @Inject
    private WorkOrderSettingService settingService;
    @Inject
    private WorkOrderManageService manageService;

    public final static String[] EXCEL_IMPORT_HEADER = {"工单编号","工单标题","工单分类","工单类型","提交人员","状态","紧急程度","提交时间"};

    @Bean(copy=true)
    @ReqMapping("/setting")
    public Object setting(WorkOrderManageSetting setting) {
        return settingService.setting(setting);
    }

    @ReqMapping("/get/setting")
    public Object getSetting() {
        return Result.success(settingService.getSetting());
    }

    @HasPermission("work:order:manage:view")
    @ReqMapping("/list/page")
    public Object listPage(Token token, JSONObject jsonObject) {
        if (!checkLogin(token)) {
            return com.kehutong.common.errcode.Result.error(0, "请先登录");
        }
        return Result.success(manageService.listPage(jsonObject, token.getUuid(), false));
    }

    @HasPermission("work:order:manage:create")
    @Bean(newInstance=true, copy=true)
    @ReqMapping("/save")
    public Object save(Token token, WorkOrderManage manage) {
        if (!checkLogin(token)) {
            return com.kehutong.common.errcode.Result.error(0, "请先登录");
        }
        if (Objects.isEmpty(manage.getHandleEmployeeNo())) {
            return Result.error(0, "处理人不能为空");
        }
        return manageService.save(manage, token, false);
    }

    @HasPermission("work:order:manage:view")
    @ReqMapping("/detail")
    public Object detail(Token token, String id) {
        return manageService.detail(token, id, true);
    }

    @HasPermission("work:order:manage:assign")
    @ReqMapping("/assign")
    public Object assign(Token token, JSONObject jsonObject){
        if (!checkLogin(token)) {
            return com.kehutong.common.errcode.Result.error(0, "请先登录");
        }

        String id = jsonObject.getString("id");
        WorkOrderManage order = Pool.get(WorkOrderManage.class, id);
        if (Objects.isNull(order)) {
            return Result.error(0, "不存在该工单");
        }

        String handleEmployeeNo = jsonObject.getString("handleEmployeeNo");
        String handleEmployeeName = jsonObject.getString("handleEmployeeName");
        order.setHandleEmployeeNo(Arrays.asList(handleEmployeeNo));
        order.setHandleEmployeeName(Arrays.asList(handleEmployeeName));
        return manageService.assign(token, jsonObject, order);
    }

    // @Bean(copy=true)
    @HasPermission("work:order:manage:del")
    @ReqMapping("/delete")
    public Object delete(Token token, WorkOrderManage manage) {
        manage.setDeleted(true);
        return manageService.delete(manage, token.getUuid());
    }

    @HasPermission("work:order:manage:view")
    @ReqMapping("/get")
    public Object get(WorkOrderManage manage) {

        return Result.success(manage);
    }

    @HasPermission("work:order:manage:operating")
    @ReqMapping("/handle/order")
    public Object handleOrder(Token token, JSONObject jsonObject){
        if (!checkLogin(token)) {
            return com.kehutong.common.errcode.Result.error(0, "请先登录");
        }
        return manageService.handleWorkOrder(token.getUuid(), token.getUsername(), jsonObject, false);
    }

    @HasPermission("work:order:manage:export")
    @ReqMapping("/export")
    public Object export(Token token, JSONObject jsonObject) throws Exception {
        if (!checkLogin(token)) {
            return com.kehutong.common.errcode.Result.error(0, "请先登录");
        }

        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", Short.MAX_VALUE);

        Page<WorkOrderManage> page = manageService.listPage(jsonObject, token.getUuid(), false);
        File dataFile = exportOrderDataFile(page.getList());
        return Result.download(dataFile);
    }

    private File exportOrderDataFile(List<WorkOrderManage> orderManageList) throws Exception {
        Workbook wb = exportOrderWorkBook(orderManageList);
        return ExcelUtil.writeXlsFile(wb, "工单列表", ".xls");
    }

    private Workbook exportOrderWorkBook(List<WorkOrderManage> orderManageList) {

        // 生成模板文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建工具
        CreationHelper helper = wb.getCreationHelper();
        //单元格样式类
        CellStyle dateCellStyle = wb.createCellStyle();
        //设置单元格格式
        dateCellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

        Sheet sheet = wb.createSheet();
        Row headerRow = sheet.createRow(0);
        int headerCellNum = 0;
        for (String s : EXCEL_IMPORT_HEADER) {
            Cell cell = headerRow.createCell(headerCellNum++);
            cell.setCellValue(s);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int cellNum = 0;
        for (int i = 0; i < orderManageList.size(); i++) {
            WorkOrderManage order = orderManageList.get(i);
            Row row = sheet.createRow(i + 1);
            cellNum = 0;
            row.createCell(cellNum++).setCellValue(order.getId());
            row.createCell(cellNum++).setCellValue(order.getName());
            StringBuffer sb = new StringBuffer();
            sb.append(order.getOneClassifyName()).append(">").append(order.getTwoClassifyName());
            row.createCell(cellNum++).setCellValue(sb.toString());
            row.createCell(cellNum++).setCellValue(order.getTypeName());
            row.createCell(cellNum++).setCellValue(order.getCreateUserName());
            row.createCell(cellNum++).setCellValue(Objects.nonNull(order.getWorkOrderState()) ? order.getWorkOrderState().getDesc() : "");
            row.createCell(cellNum++).setCellValue(Objects.nonNull(order.getEmergency()) ? order.getEmergency().getDesc() : "");

            row.createCell(cellNum++).setCellValue(sdf.format(order.getCreateTime()));
        }

        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            if (i == 0) {
                // id列不调整
                continue;
            }
            // 自动列宽
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;
    }

    private boolean checkLogin(Token token){
        if (Objects.isNull(token)) {
            return false;
        }

        if (Objects.isEmpty(token.getUuid()) && Objects.isEmpty(token.getUsername())) {
            return false;
        } else {
            return true;
        }
    }
}
